package cn.edu.cdut.service;

import cn.edu.cdut.dao.DisciplineInfoDao;
import cn.edu.cdut.dao.PlanCourseInfoDao;
import cn.edu.cdut.dto.MyRes;
import cn.edu.cdut.model.PlanCourseInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Iterator;

/**
 * Author  kobe
 * Created on 2017-05-31-17:15
 */
@Service
public class PlanCourseService {
        @Autowired
        private PlanCourseInfoDao planCourseInfoDao;


        @Transactional
        public MyRes getAllCourse() {

                Iterable<PlanCourseInfo> specIterable = planCourseInfoDao.findAll();
                //转换为Json字符串
                ObjectMapper mapper = new ObjectMapper();
                Iterator iter = specIterable.iterator();
                String[] resArr = new String[(int)planCourseInfoDao.count()];
                int i = 0;
                while(iter.hasNext()){
                        try {
                                resArr[i] = mapper.writeValueAsString(iter.next());
                                i++;
                        } catch (JsonProcessingException e) {
                                e.printStackTrace();
                                return new MyRes(201, "获取课程信息失败！", null);
                        }
                }
                return new MyRes(200, null, resArr);
        }

        //添加课程
        @Transactional
        public MyRes addCourses(PlanCourseInfo planCourseInfo) {
                planCourseInfoDao.save(planCourseInfo);
                return new MyRes(200, "提交成功！", null);
        }

        //修改课程信息
        @Transactional
        public MyRes updateCourse(PlanCourseInfo planCourseInfo) {
                planCourseInfoDao.save(planCourseInfo);
                return new MyRes(200, "提交成功！", null);
        }

        //单个删除课程信息
        @Transactional
        public MyRes removeSpeciality(Long id) {
                planCourseInfoDao.delete(id);
                return new MyRes(200, "删除成功！", null);
        }
}




